﻿using Snowflake;
using System;
using System.Net;
using System.Net.Sockets;

namespace ProjectManageSystemApi.Utilities
{
    public class UniqueKeyTool
    {
        readonly IdWorker worker;
        public UniqueKeyTool()
        {
            int workerId = GetId(GetLocalIp());
            int datacenterId = GetId(GetCompanyName());
            worker = new IdWorker(workerId, datacenterId, new Random().Next());
        }
        public long Next()
        {
            return worker.NextId();
        }
        private int GetId(string seed)
        {
            if (string.IsNullOrWhiteSpace(seed))
            {
                seed = Guid.NewGuid().ToString("N");
            }

            System.Globalization.StringInfo s = new System.Globalization.StringInfo(seed);

            int sum = 0;
            for (int i = 0, index = 0, length = s.LengthInTextElements; i < length; i++)
            {
                var charValue = (int)seed[index];
                sum += charValue;
                index += charValue >= 0x10000 ? 2 : 1;
            }
            return sum % 32;
        }
        private string GetCompanyName()
        {
            return System.Environment.GetEnvironmentVariable("ComputerName");
        }
        private string GetLocalIp()
        {
            string name = Dns.GetHostName();
            IPAddress[] ipadrlist = Dns.GetHostAddresses(name);
            if (ipadrlist.Length == 0)
            {
                return "127.0.0.1";
            }
            foreach (IPAddress ipa in ipadrlist)
            {
                if (ipa.AddressFamily == AddressFamily.InterNetwork)
                {
                    return ipa.MapToIPv4().ToString();
                }
            }
            return ipadrlist[0].MapToIPv4().ToString();
        }
    }
}
